//
//  ASColListController.swift
//  soapp
//
//  Created by zhu xietong on 2018/4/24.
//

import Foundation
import Kingfisher
import Eelay
import JoLoading
import AsyncDisplayKit

open class ASColListView:JoView,LoadingPresenter,ASCollectionVConfig,ASCollectionDelegateFlowLayout
{
    public var loadingPresenterInset: UIEdgeInsets{
        get{
            return .zero
        }
    }
    var __loadIndex = 0{
        didSet{
            if __loadIndex == 1{
                viewDidLoad()
            }
        }
    }
    
    public var LoadingClass:JoLoading.Type{
        get{
//            print("+++++++++pppp|\(SimpleLoading.self)")
            return SimpleLoading.self
        }
    }
//    public var LoadingClass:JoLoading.Type = SimpleLoading.self


    open var sections:TP.section{
        get{
            let sec:TP.section = [
                []
            ]
            return sec
        }
    }
    
    open var selector:TP.selector{
        get{
            let sel = TP.selector()
            assertionFailure("Must override selector:TP.selector,\(#file) \(#line)")
            //            alert("Must override selector:TP.selector")
            return sel
        }
    }
    
    open override func willMove(toSuperview newSuperview: UIView?) {
        super.willMove(toSuperview: newSuperview)
        __loadIndex = __loadIndex + 1
    }
    
    open func viewDidLoad(){
        
    }
    
    
    public var collectionNode:ASCollectionNode!
    open var collectionView:UICollectionView{
        get{
            return collectionNode.view
        }
    }
    
    public var so_constrains = [NSLayoutConstraint]()
    public var edegs:(top:CGFloat,left:CGFloat,bottom:CGFloat,right:CGFloat) = (0,0,0,0)
    public required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    public var flowLayout = UICollectionViewFlowLayout()
    required public init() {
        flowLayout = UICollectionViewFlowLayout()
        collectionNode = ASCollectionNode(collectionViewLayout: flowLayout)
        flowLayout.minimumLineSpacing = 10
        flowLayout.minimumInteritemSpacing = 10
        super.init()
       
        //        let w = Swidth/2.0 - 10
        //        flowLayout.itemSize = CGSize(width: w, height: w)
        
        
    }
    
    
    
    public func load(sections:TP.section,selector:TP.selector)
    {
        collectionNode.load(sections: sections, selector: selector)
    }
    
    public var contentInsetView: UIScrollView? {
        get{
            return self.collectionView
        }
    }
    
    open override func addLayoutRules() {
        
        
        layCollection(collectionView: collectionView)
        
        configCollections(nodes: collectionNode)
        
        
    }
    
    open func layCollection(collectionView:UIView)
    {
        jo_contentView.eelay = [
            [collectionView,[ee.T.L.B.R]]
        ]
    }
    
    
    public func remove_constains()
    {
        self.jo_contentView.removeConstraints(self.so_constrains)
    }
    
    open func touch(cell: Any, actionID: String, model: NSMutableDictionary) {
    }
    
    
    open func reloadDataActionHappensHere(){
        let count = collectionNode.dataSource?.collectionNode?(collectionNode, numberOfItemsInSection: 0) ?? 0
        if count > 2 {
            for row in 0...(count-1)
            {
                indexPathesToBeReloaded.append(IndexPath(row:row,section:0))
            }
        }
        self.collectionNode.reloadData()
        collectionNode.waitUntilAllUpdatesAreProcessed();
        
    }
    public var indexPathesToBeReloaded: [IndexPath] = []
    
    open func checkCell(cell:ASCellNode,indexPath: IndexPath) {
        
    }
    
    open func collectionNode(_ collectionNode: ASCollectionNode, didSelectItemAt indexPath: IndexPath) {
        
    }
    
    
    open func collectionNode(_ collectionNode: ASCollectionNode, nodeForItemAt indexPath: IndexPath) -> ASCellNode {
        
        let cell = collectionNode.cellNode(indexPath: indexPath, fillModel: true, delegate: self)
        cell.neverShowPlaceholders = true
        if let cnode = cell as? JoCellNode
        {
            cnode.delegate = self
        }
        checkCell(cell: cell, indexPath: indexPath)
        if indexPathesToBeReloaded.contains(indexPath) {
            let oldCellNode = collectionNode.nodeForItem(at: indexPath)
            cell.neverShowPlaceholders = true
            oldCellNode?.neverShowPlaceholders = true
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: {
                cell.neverShowPlaceholders = false
                if let indexP = self.indexPathesToBeReloaded.firstIndex(of: indexPath) {
                    self.indexPathesToBeReloaded.remove(at: indexP)
                }
            })
        }
        return cell
    }
    
    open func collectionNode(_ collectionNode: ASCollectionNode, nodeBlockForItemAt indexPath: IndexPath) -> ASCellNodeBlock {
        return collectionNode.cellBlock(indexPath: indexPath, nodeBuild: ({_ in})).block

    }
    
    
    
    public func collectionView(_ collectionView: ASCollectionView, constrainedSizeForNodeAt indexPath: IndexPath) -> ASSizeRange {
        return ASSizeRange.collectionNode(collectionNode: collectionNode, indexPath: indexPath)
    }
    
    //    public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
    //
    //    }
    
    
    
    deinit {
        
    }
    
    
    required public init(frame: CGRect) {
        fatalError("init(frame:) has not been implemented")
    }
    
    
    
    open func mo_request_send() {
        
    }
    
    
    open func mo_request_load(obj: Any) {
        
    }
    
    public func mo_request_alert(msg: String, title: String, bt_title: String) {
        weak var wself = self
        if bt_title.len < 1
        {
            loadingV.show(message: msg, title: title)
            return
        }
        self.loadingV.handle(message: msg, title: title, button: bt_title, handAction: {
            wself?.loadingV.loading()
            wself?.mo_request_send()
        })
    }
}
